<template>
  <el-dialog title="提示" :visible.sync="addCateDialog" width="50%" @close="addCateClose">
    <el-form :model="addCateForm" :rules="addCateRules" ref="addCateRef" label-width="100px">
      <el-form-item label="分类名称" prop="cat_name">
        <el-input v-model="addCateForm.cat_name"></el-input>
      </el-form-item>
      <el-form-item label="父级分类">
        <el-cascader
          v-model="selectedCate"
          :options="parentCateList"
          expandTrigger="hover"
          :props="cathTrigerProps"
          @change="parentCateChange"
          clearable
          change-on-select
        ></el-cascader>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="addCateDialog = false">取 消</el-button>
      <el-button type="primary" @click="addCate">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
export default {
  props: {
    visible: {
      type: Boolean
    },
    parentCateList: {
      type: Array
    }
  },
  data() {
    return {
      addCateDialog: false,
      addCateForm: {
        cat_name: '',
        cat_level: 0,
        cat_pid: 0
      },
      addCateRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      //   指定级联选择器的配置对象
      cathTrigerProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      selectedCate: []
    }
  },
  methods: {
    parentCateChange() {
      if (this.selectedCate.length > 0) {
        this.addCateForm.cat_level = this.selectedCate.length
        this.addCateForm.cat_pid = this.selectedCate[
          this.selectedCate.length - 1
        ]
      } else {
        this.addCateForm.cat_level = 0
        this.addCateForm.cat_pid = 0
      }
    },
    addCate() {
      this.$refs.addCateRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post(
          'categories',
          this.addCateForm
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加分类失败')
        }
        this.$message.success('添加分类成功')
        this.$emit('addCateSuccess')
        this.addCateDialog = false
      })
    },
    addCateClose() {
      this.$refs.addCateRef.resetFields()
      this.selectedCate = []
      this.addCateForm.cat_level = 0
      this.addCateForm.cat_pid = 0
    }
  },
  watch: {
    visible: function(val) {
      this.addCateDialog = val
    },
    addCateDialog: function(val) {
      this.$emit('update:visible', val)
    }
  }
}
</script>
<style lang="less" scoped>
.el-cascader {
  width: 100%;
}
</style>
